package com.xxx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.mapper.EarlyStatisticsMapper;
import com.xxx.pojo.*;
import com.xxx.service.*;
import com.xxx.utils.ExportUtil;
import com.xxx.vo.MattersVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/early")
@RestController
public class EarlyWarningController {

    @Autowired
    private EarlyWarningService earlyWarningService;

    @Autowired
    private MetricsService metricsService;

    @Autowired
    private MattersService mattersService;


    @Autowired
    private EarlyStatisticsMapper earlyStatisticsMapper;

    @Autowired
    private RangeWarningService rangeWarningService;

    @Autowired
    private UserOperateService userOperateService;

    @Transactional
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('sys:add:early')")
    public Result addEarly(@RequestBody EarlyWarning earlyWarning){
        if (Objects.isNull(earlyWarning)){
            throw new RuntimeException("预警格式错误!");
        }
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        earlyWarning.setCreateUser(loginUser.getUser().getName());
        earlyWarning.setUpdateTime(LocalDateTime.now());
        boolean save = earlyWarningService.save(earlyWarning);
        if (!save){
            return Result.error("添加失败!");
        }
        userOperateService.addLogManage("预警管理","添加预警决策结果","添加");
        return Result.success("添加成功!");
    }

    /**
     * 根据指标值查询结果
     * @param warningId
     * @param value
     * @return
     */
    @Transactional
    @GetMapping("/selectOutcome/{warningId}/{value}")
    public Result selectEarlyOutcome(@PathVariable Integer warningId,@PathVariable("value") Double value){
        LambdaQueryWrapper<Metrics> wrapper = new LambdaQueryWrapper<Metrics>().eq(warningId != null && warningId > 0, Metrics::getWarningId, warningId);
        List<Metrics> list = metricsService.list(wrapper);
        Integer outcome = 0;
        List<Double> range = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (value >= list.get(i).getStart()){
                outcome = list.get(i).getLevel();
                range.clear();
                range.add(list.get(i).getStart());
                range.add(list.get(i).getEnd());
                //最后一个值
                if (i == list.size()-1 && list.get(i).getEnd() == -1){
                    outcome = 3;
                    range.clear();
                    range.add(list.get(i).getStart());
                }else if (i == list.size()-1 && list.get(i).getEnd() != -1){
                    throw new RuntimeException("输入的值有误");
                }

            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("outcome", outcome.toString());
        map.put("range",range.toString());
        return Result.success("",map);
    }

    //预警反腐
    @Transactional
    @PostMapping("/corruption")
    public Result EarlyCorruption(@RequestBody Matters matters, @RequestParam("current") Integer current, @RequestParam("size") Integer size){
        if (Objects.isNull(matters)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        IPage iPage = new Page(current,size);
        LambdaQueryWrapper<Matters> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Matters::getStatus,1);
        IPage page = mattersService.page(iPage, wrapper);
        List<Matters> mattersList =page.getRecords();
        List<MattersVo> list = mattersList.stream().map(o -> {
            EarlyWarning warning = earlyWarningService.getOne(new LambdaQueryWrapper<EarlyWarning>().eq(EarlyWarning::getMattersId,o.getId()));
            MattersVo mattersVo = new MattersVo();
            BeanUtils.copyProperties(o, mattersVo);
            mattersVo.setEarlyWarning(warning);
            return mattersVo;
        }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total", page.getTotal());
        return Result.success("",map);
    }

    @Transactional
    @PostMapping("/selectStatistics")
    public Result selectEarlyStatistics(@RequestBody EarlyStatistics earlyStatistics,@RequestParam("current") Integer current,@RequestParam("size") Integer size
    ,@RequestParam(required = false) String startTime,@RequestParam(required = false) String endTime){
        Integer start = (current-1)*size;
        Integer total = earlyStatisticsMapper.selectPageTotal(earlyStatistics, start, size, startTime, endTime);
        List<EarlyStatistics> earlyStatisticsList = earlyStatisticsMapper.selectEarlyStatisticsByCondition(earlyStatistics,start,size,startTime,endTime);

        for (EarlyStatistics statistics : earlyStatisticsList) {
            String[] split = statistics.getClassification().split(",");
            String s = split[0];
            RangeWarning byId = rangeWarningService.getById(s);
            statistics.setClassification(byId.getClassification());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",earlyStatisticsList);
        map.put("total", total);
        return Result.success("",map);
    }

    @Transactional
    @GetMapping("/export")
    @PreAuthorize("hasAnyAuthority('sys:select:early')")
    public void exportUserExcel(HttpServletResponse response) {
        try {
            ExportUtil.setExcelResponseProp(response, "预警决策结果统计");
            List<EarlyStatistics> earlyStatisticsList = earlyStatisticsMapper.selectAll();
            for (EarlyStatistics statistics : earlyStatisticsList) {
                String[] split = statistics.getClassification().split(",");
                String s = split[0];
                RangeWarning byId = rangeWarningService.getById(s);
                statistics.setClassification(byId.getClassification());
            }
            EasyExcel.write(response.getOutputStream())
                    .head(EarlyStatistics.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("预警决策结果统计")
                    .doWrite(earlyStatisticsList);
            userOperateService.addLogManage("预警管理","导出预警决策结果统计","导出");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
